<template>
  <el-container>

    <el-header height=10% style="margin: 0;padding: 0;height: 59px">
      <blank-top-menu></blank-top-menu>
    </el-header>

    <el-main class="main">
      <el-card class="register-card">
        <template #header>
          <div class="card-header">
            <span>注册入口</span>
          </div>
        </template>

        <el-form
            label-width="100px"
            label-position="left"
            size="small"
            inline="inline"
            :rules="dataRule"
            ref="formdata"
            :model="formObj"
        >
          <el-row justify="center">
            <el-form-item label="账户" prop="userName">
              <el-input v-model="formObj.userName"/>
            </el-form-item>
          </el-row>

          <el-row justify="center">
            <el-form-item label="密码" prop="password">
              <el-input

                  v-model="formObj.password"/>
            </el-form-item>
          </el-row>

          <el-row justify="center">
            <el-form-item label="确认密码" prop="passwordAgain">
              <el-input type="password"
                        show-password
                        v-model="formObj.passwordAgain"/>
            </el-form-item>
          </el-row>

          <el-row justify="center">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formObj.email"/>
            </el-form-item>
          </el-row>

          <el-row justify="space-evenly">
            <el-col :span="6" style="margin-left: 12px">
              <el-form-item label="验证码" prop="captcha"></el-form-item>
            </el-col>
            <el-col :span="6">
              <el-input v-model="formObj.captcha"/>
            </el-col>
            <el-col :span="6">
              <!--              <el-button class="but" @click="sendCaptcha">获取验证码</el-button>-->
              <div>
                <el-button v-show="showSend" @click="sendCaptcha" >获取验证码</el-button>
                <span v-show="!showSend" class="count">{{secLeft}} s</span>
              </div>
            </el-col>
            <el-row justify="center">
              <el-form-item label="用户协议">
                <el-checkbox v-model="whetherAgree"/>
                <div @click="centerDialogVisible=true" class="agreeContent">同意用户协议</div>
              </el-form-item>
            </el-row>
          </el-row>

          <el-row justify="center">
            <el-popconfirm title="确认取消吗?" @confirm="go2login" >
              <template #reference>
                <el-button>取消</el-button>
              </template>
            </el-popconfirm>
            <el-button class="but" @click="register">注册</el-button>
          </el-row>

        </el-form>
      </el-card>

      <el-dialog
          v-model="centerDialogVisible"
          title="用户协议" width="30%"
          center
          class="dialog"
      >
    <span style="white-space: pre-wrap;">
        {{content}}
    </span>
        <template #footer>
      <span class="dialog-footer">
<!--        用户协议-->
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" class="but" @click="agreeAndContinue">
          同意并继续
        </el-button>
      </span>
        </template>
      </el-dialog>
    </el-main>


  </el-container>
</template>

<script>
import BlankTopMenu from "@/components/blank-top-menu";
import { ref } from 'vue'
import axios from 'axios'
import {ElMessage} from "element-plus";
let centerDialogVisible = ref(false)// eslint-disable-line no-unused-vars
export default {
  name: "register-frame",
  components:{BlankTopMenu},
  data(){
    return{
      content:'本交易平台仅提供基于NFT的数字作品交易，用户所上传的任何数字作品的版权与内容以及用户个人需满足以下条件与承诺：\n' +'\n'+
          '一、 作品内容绿色健康、积极向上，不包含任何违法乱纪内容；\n' +
          '二、 作品保证原创，不存在任何侵犯版权、知识产权等他人权益的行为；\n' +
          '三、 用户必须保证完成实名认证，且实名信息必须为本人信息；\n' +
          '四、 不以任何方式在未获取作品使用权和所有权的情况下于其他平台发布本平台提供的作品详细信息；\n' +
          '五、 一切因访问本交易平台引致之任何意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其所造成的损失，本交易平台概不负责，亦不承担任何法律责任；\n' +
          '六、 任何网友所发布的链接及得到之资讯，产品及服务均系网友个人行为，并不反映任何代表本平台的意见，本平台不为其承担任何法律责任；\n' +
          '七、 任何单位或个人认为本平台的内容可能涉嫌侵犯其合法权益，应该及时向本平台书面反馈，并提供身份证明、权属证明及详细侵权情况证明。本平台在收到上述法律文件后，将会尽快核实并移除被控侵权内容；\n' +'\n'+
          '注：本协议签署同意后将通过本平台进行区块链上链',
      formObj: {
        userName:'',
        password:'',
        passwordAgain:'',
        email:'',
        captcha:'',
      },
      showSend:true,
      secLeft:60
    }
  },
  setup() {
    let checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    }

    let checkName  = (rule, value, callback) => {
      if(!value){
        return callback(new Error('账号不能为空!'))
      } else {
        let b = 0,c=0
        for(var i = 0 ; i < value.length ; i ++ ){
          if (value[i] <= 'z' && value[i] >= 'a'){
            b = 1
          }else{
            c = 1
          }
        }
        if(b==0||c==1){
          return callback(new Error('用户名应由小写字母组成!'))
        }
      }
    }


    let checkPwd = (rule, value, callback) => {
      if(!value){
        return callback(new Error('密码不能为空!'))
      } else {
        let a = 0 , b = 0,c=0
        for(var i = 0 ; i < value.length ; i ++ ){
          if(value[i] <= '9' && value[i] >= '0'){
            a = 1
          }else if (value[i] <= 'z' && value[i] >= 'a'){
            b = 1
          }else{
            c = 1
          }
        }
        if(a==0||b==0||c==1){
          return callback(new Error('密码应由数字+小写字母组成!'))
        }
      }
    }

    let checkPwdAgain = (rule, value, callback) => {
      if(!value){
        return callback(new Error('确认密码不能为空!'))
      }
    }

    let centerDialogVisible = ref(false)

    let dataRule =  {
      userName:[
        {required:true , message :"请输入用户名",trigger:"blur"},
        { validator: checkName, trigger: "blur" }
      ],
      password: [
        {required:true , message :"请输入密码",trigger:"blur"},
        { validator: checkPwd, trigger: "blur" }
      ],
      passwordAgain: [
        {required:true , message :"请重复输入密码",trigger:"blur"},
        { validator: checkPwdAgain, trigger: "blur" }
      ],
      email: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        { validator: checkEmail, trigger: "blur" }
      ],
      captcha:[
        { required: true, message: "请输入验证码", trigger: "blur" },
      ]
    }

    let whetherAgree = ref(false)
    return {
      centerDialogVisible,
      // checkEmail,
      dataRule,
      whetherAgree
    }
  },
  methods: {
    go2login:function (){
      this.$router.push("/login")
    },
    cancel:function (){
      this.centerDialogVisible = false
      this.whetherAgree = false
    },
    register: function () {
      // eslint-disable-next-line no-unused-vars
      // console.log("!@#!@#!@#");
      // this.$refs.formdata.validate((valid) => {
      let a = 0 , b = 0 , c = 0
      for(var i = 0 ; i < this.formObj.password.length ; i ++ ){
        if(this.formObj.password[i] <= '9' && this.formObj.password[i] >= '0'){
          a = 1
        }
        else if (this.formObj.password[i] <= 'z' && this.formObj.password[i] >= 'a'){
          b = 1
        } else{
          c = 1
        }
      }
      let d = 0 , e = 0
      for(var j = 0 ; j < this.formObj.userName.length ; j ++ ){
        if (this.formObj.userName[j] <= 'z' && this.formObj.userName[j] >= 'a'){
          d = 1
        }else{
          e = 1
        }
      }
      if(this.whetherAgree == false){
        this.$message.error('请同意用户协议！')
      } else if(this.formObj.email == '' || this.formObj.password == '' || this.formObj.passwordAgain == '' ||
      this.formObj.userName == '' || this.formObj.captcha == ''){
        this.$message.error('请填写所有信息！')
      } else if (this.formObj.passwordAgain !== this.formObj.password ) {
        this.$message.error('两次请输入相同的密码')
      } else if(a == 0 || b ==0 || c == 1){
          this.$message.error("密码格式不正确！")
      } else if(d == 0 || e==1){
        this.$message.error("账号格式不正确！")
      } else {
        let form=new FormData();
        form.append('username',this.formObj.userName)
        form.append('password',this.formObj.password)
        form.append('email',this.formObj.email)
        form.append('captcha',this.formObj.captcha)
        axios
            .post('http://120.48.51.66:8081/user/register', form).then((response)=>{
          console.log(response)
          if (response.data.code == 4000){
            ElMessage({
              message:'用户名重复!',
              type:'error'
            })
          }else if(response.data.code == 7000){
            ElMessage({
              message:'验证码错误!',
              type:'error'
            })
          } else if(response.data.code == 5000 || response.data.code == 6000){
            ElMessage({
              message:'注册异常',
              type:'error'
            })
          }
          else if(response.data.code == 200){
            ElMessage({
              message:'注册成功',
              type:'success'
            })
            this.$router.push("/login")
          }
        })
      }
      // })

    },
    sendCaptcha: function () {
      let form = new FormData()
      // this.$refs.formdata.validate((valid) => {
      if (this.formObj.email == '') {
        this.$message.error('请填写邮箱!')
      } else {
        this.showSend = false
        let timer = setInterval(()=>{
          this.secLeft --
          if(this.secLeft == 0 ){
            this.showSend = true
            this.secLeft = 60
            clearInterval(timer)
          }
        },1000)
        form.append('receiver', this.formObj.email)
        axios.post('http://120.48.51.66:8081/user/sendCaptcha', form).then((response)=>{
          console.log('response',response)
          if (response.data.code===200){
            ElMessage({
              message:'发送验证码成功',
              type:'success'
            })
          }else if (response.data.code == 6000){
            ElMessage({
              message:'验证码发送异常',
              type:'error'
            })
          }
        })
      }
      // })
    },
    agreeAndContinue:function (){
      this.centerDialogVisible = false
      this.whetherAgree = true
    },
  }
}
</script>

<style>
html,
body,
.app_container,
.el-container{
  padding: 0;
  margin: 0;
  height: 100vh;
}


.main{
  background:url("@/assets/background.jpg");
  background-repeat: no-repeat;
  background-position: left top;
  background-size: 100% 100%;
}


.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.register-card {
  width: 400px;
  margin-left: 60%;
  margin-top: 11%;
  border-radius: 22px;
  height: 400px;
}
.but{
  background-color: #4C8ADA;
  color: white;
}
.radio{
  color: darkgray;
}

.agreeContent:hover{
  cursor: pointer;
  color: #4484ce;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
.dialog{
  border-radius: 20px;
}
</style>
